package cs340.stormtroopers.database;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;

import cs340.stormtroopers.hypeerweb.Node;

public class NormalNodeDelegate extends Delegate
{
	
	public NormalNodeDelegate(Node node)
	{
		super(node);
	}

	@Override
	public void insertIntoDatabase(Connection connection) throws SQLException, IOException, ClassNotFoundException
	{
		// System.out.println("Inserting node with webId: " + delegate.getWebIdValue());
		PreparedStatement insertNodeStatement = connection
				.prepareStatement("INSERT OR IGNORE INTO Node(WebId, Height, FoldId, SurrogateFoldId, InverseSurrogateFoldId) VALUES (?, ?, ?, ?, ?);");
		insertNodeStatement.setInt(1, delegate.getWebIdValue());
		insertNodeStatement.setInt(2, delegate.getWebId().getHeight());
		insertNodeStatement.setInt(3, delegate.getFold().getWebIdValue());
		insertNodeStatement.setInt(4, delegate.getSurrogateFold()
				.getWebIdValue());
		insertNodeStatement.setInt(5, delegate.getInverseSurrogateFold()
				.getWebIdValue());
		insertNodeStatement.addBatch();
		//connection.setAutoCommit(false);
		insertNodeStatement.executeBatch();
		//connection.setAutoCommit(true);
		insertNodeStatement.close();
		
		// now insert neighbors and surrogate neighbors
		HyPeerWebDatabase db = HyPeerWebDatabase.getSingleton();
		db.saveNodeDelegates(NeighborDelegate.wrap(delegate, delegate.getNeighbors()));
		db.saveNodeDelegates(SurrogateNeighborDelegate.wrap(delegate, delegate.getDownPointers()));
	}

	public static Iterator<Delegate> wrap(final Iterable<Node> nodes)
	{
		return new Iterator<Delegate>() {
			private Iterator<Node> iterator = nodes.iterator();
			@Override
			public boolean hasNext()
			{
				return iterator.hasNext();
			}

			@Override
			public Delegate next()
			{
				return new NormalNodeDelegate(iterator.next());
			}

			@Override
			public void remove()
			{
				throw new UnsupportedOperationException();
			}
			
		};
	}
}
